<template>
  <div>
    <!-- @click-right="onClickRight" -->
    <van-nav-bar
      title="编辑昵称"
      left-text="取消"
      right-text="保存"
      @click-left="$emit('left-close')"
      @click-right="onSave"
    />

    <van-field
      v-model="name"
      type="textarea"
      maxlength="8"
      placeholder="请输入新昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { setUserProfile } from '@/api/user.js'
export default {
  data () {
    return {
      name: this.value
    }
  },

  props: {
    value: {
      type: String,
      required: true
    }
  },

  created () {

  },

  methods: {
    // 点击保存
    async onSave () {
      if (this.name.trim() === '') return this.$toast('请输入必要的昵称')
      try {
        await setUserProfile({
          name: this.name
        })
        this.$toast('修改昵称成功')
        this.$emit('left-close')
        this.$emit('input', this.name)
      } catch (err) {
        if (err.response && err.response.status === 409) {
          return this.$toast('亲,用户名已存在')
        }
        this.$toast('修改昵称失败')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
